package com.xzx.mr.topn;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * @author xinzhixuan
 * @version V1.0
 * @date 2019/8/9 22:17
 */
public class TopNMapper extends Mapper<LongWritable, Text, Text, TopNFlowBean> {

    private TopNFlowBean k;
    private Text v;

    // 记录钱top n个元素
    private TreeMap<TopNFlowBean, Text> treeMap = new TreeMap<>();

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 13470253144	180	180	360
        String line = value.toString();
        String[] split = line.split("\t");
        k = new TopNFlowBean();
        v = new Text();

        v.set(split[0]);
        k.setUpFlow(Long.parseLong(split[1]));
        k.setDownFlow(Long.parseLong(split[2]));
        k.setSumFlow(Long.parseLong(split[3]));

        treeMap.put(k, v);

        if (treeMap.size() > 10) {
            // 移除最后一个
            treeMap.remove(treeMap.lastKey());
        }
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        // 再这里统一输出
        Iterator<TopNFlowBean> iterator = treeMap.keySet().iterator();
        while (iterator.hasNext()) {
            TopNFlowBean next = iterator.next();
            context.write(treeMap.get(next), next);
        }
    }
}
